package com.yuxi.Controller.Impl;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.google.gson.Gson;
import com.yuxi.Config.ConfigStatic;
import com.yuxi.Dao.InformationDao;
import com.yuxi.Dao.UserInfoDao;
import com.yuxi.Entity.Information;
import com.yuxi.Entity.PrisonStructure;
import com.yuxi.Entity.UserInfo;
import com.yuxi.Entity.UserPosition;
import com.yuxi.Entity.UserStructure;
import com.yuxi.Entity.UserView;
import com.yuxi.Request.Page;
import com.yuxi.Request.UserQuery;
import com.yuxi.Response.Msg;
import com.yuxi.Response.Obj;
import com.yuxi.Service.PrisonService;
import com.yuxi.Service.UserQueryService;
import com.yuxi.Service.UserService;
import com.yuxi.Util.GsonUtil;
import com.yuxi.Util.IPUtil;
import com.yuxi.Util.MyMd5Util;
import com.yuxi.Util.VerifyCodeUtil;
import com.yuxi.view.UserPowerView;

import sun.net.util.IPAddressUtil;
@Controller
public class UserController implements com.yuxi.Controller.UserController {
	@Autowired
	private UserService  userService;
	@Autowired
	private PrisonService prisonService;
	@Autowired
	private UserQueryService userQueryService;
	@Autowired
	private UserInfoDao userInfoDao;
	
	private GsonUtil gson=new GsonUtil();
	@Override
	public String userLogin(String userAccount, String pwd,String verifyCode,HttpSession session,HttpServletRequest request,HttpServletResponse res) {
		if(userAccount.isEmpty()||pwd.isEmpty()){
			Msg msg=new Msg(false, "登录名或密码不能为空", System.currentTimeMillis(), "10001", "登录操作");
			return 	gson.toJson(msg);
		}
		if(ConfigStatic.VerifyCodeOff&&verifyCode.isEmpty()){
			Msg msg=new Msg(false, "验证码不能为空", System.currentTimeMillis(), "10002", "登录操作");
			return 	gson.toJson(msg);
		}
		
		
		if(ConfigStatic.VerifyCodeOff){
			String sessionVerifyCode=(String)session.getAttribute("verifyCode");
			if(sessionVerifyCode==null){
				Msg msg=new Msg(false, "验证码过期请重新刷新验证码", System.currentTimeMillis(), "10004", "登录操作");
				return 	gson.toJson(msg);
			}
			sessionVerifyCode=sessionVerifyCode.toLowerCase();
			verifyCode=verifyCode.toLowerCase();
			
			if(!sessionVerifyCode.equals(verifyCode)){
				Msg msg=new Msg(false, "验证码错误", System.currentTimeMillis(), "10003", "登录操作");
				return 	gson.toJson(msg);
			}
		}
		String ip=IPUtil.getIpAddr(request);
		pwd=MyMd5Util.stringToMd5(pwd);		
		UserInfo u=userService.userLogin(userAccount, pwd,ip);
		if(u==null){
			Msg msg=new Msg(false, "登录名或密码错误", System.currentTimeMillis(), "10002", "登录操作");
			return 	gson.toJson(msg);
		}else{
			if(!u.isEnable()){
				Msg msg=new Msg(false, "账户已被停用", System.currentTimeMillis(), "10003", "登录操作");
				return 	gson.toJson(msg);
			}
			session.setAttribute("user", u);
			if(!u.getUserName().equals("root")){
				UserView userView= prisonService.getUserViewById(u.getUserId());
				session.setAttribute("userView", userView);	
				UserPowerView uPower=userService.getUserPowerViewByUserId(u);
				session.setAttribute("userPowerView",uPower);			
			}
			
			String str="/yuxi/model/home/index.jsp?menuId=0";
			if(u.getUserName().equals("root")){
				str="/yuxi/cms/index.html";
			}
			Obj msg=new Obj(true, "登陆成功", str, System.currentTimeMillis(), null, "登录操作");
			return 	gson.toJson(msg);
		}

	}
	@Override
	public String addUser(UserInfo userInfo,int positionId,String positionName,int structureId,String structureName,int roleId,HttpSession session,HttpServletRequest request) {
		try{
			String ip=IPUtil.getIpAddr(request);
			UserInfo u=userService.userCreateOneUser(userInfo, userService.getCurLoginUser(session), ip, positionId,positionName,structureId,structureName,roleId);
			if(u==null){
				Msg msg=new Msg(false, "添加用户失败",System.currentTimeMillis(), "10001", "创建用户");
				return gson.toJson(msg);
			}
			Msg msg=new Msg(true, "添加用户成功",System.currentTimeMillis(), null, "创建用户");
			return gson.toJson(msg);
		}catch(Exception e){
			Msg msg=new Msg(false, "添加用户失败",System.currentTimeMillis(), "10002", "创建用户");
			return gson.toJson(msg);
		}
		
	}

	@Override
	public String addInfo(Information information, HttpSession session) {		
//		List<PrisonStructure> p=userService.userGetsafetyPortList(userService.getCurLoginUser(session));
//		return gson.toJson(p);
		return null;
	}

	@Override
	public void getVerifyCode(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		 // 禁止图像缓存。		
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
	    // 将图像输出到Servlet输出流中。
	    ServletOutputStream sos;
		try {	
			String verifyCode=VerifyCodeUtil.generateVerifyCode(4);	
			verifyCode=verifyCode.toLowerCase();
			session.setAttribute("verifyCode", verifyCode);			
			sos = response.getOutputStream();		   
			VerifyCodeUtil.outputImage(120, 50, sos, verifyCode);			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public String getUserList(int structId,  HttpServletRequest request, HttpSession session) {
		try{
			List<UserInfo> u=userService.userGetStructUserList(structId);
			Obj rso=new Obj(true, "获取用户列表成功", u, System.currentTimeMillis(), null, "根据部门获取用户列表");
			return gson.toJson(rso);
		}catch(Exception e){
			e.printStackTrace();
			Obj rso=new Obj(false, "获取用户列表失败", null, System.currentTimeMillis(), "1001", "根据部门获取用户列表");
			return gson.toJson(rso);
		}
	}

	@Override
	public String getUserCreateUserList(UserQuery userQuery, Page<UserView> p, HttpSession session) {
		UserInfo u=userService.getCurLoginUser(session);
		Page<UserView> rsp=userService.getUserList(userQuery, u, p);
		return gson.toJson(rsp);
	}

	@Override
	public String getFlowCount(HttpSession session) {
		UserInfo u=userService.getCurLoginUser(session);
		UserPowerView power=userService.curLoginUserPowerView(session);
		Obj obj=new Obj(true, "获取待处理信息汇总成功", userQueryService.getFlowCount(u,power),
				System.currentTimeMillis(), null, "获取待处理信息汇总");
		return gson.toJson(obj);
	}

	@Override
	public String stopUserById(Integer userId, HttpSession session) {
		UserInfo user=userService.getCurLoginUser(session);
		if(userId==null){
			Msg msg=new Msg(false, "停用失败[参数错误]", System.currentTimeMillis(), "1002",  "停用账户");
			return gson.toJson(msg);
		}
		if(userService.stopUserById(userId, user)){
			Msg msg=new Msg(true, "停用成功", System.currentTimeMillis(), null,  "停用账户");
			return gson.toJson(msg);
		}else{
			Msg msg=new Msg(false, "停用失败", System.currentTimeMillis(), "1001",  "停用账户");
			return gson.toJson(msg);
		}
	
	}

	@Override
	public String enableUserById(Integer userId, HttpSession session) {
		UserInfo user=userService.getCurLoginUser(session);
		if(userId==null){
			Msg msg=new Msg(false, "停用失败[参数错误]", System.currentTimeMillis(), "1002",  "停用账户");
			return gson.toJson(msg);
		}
		if(userService.enableUserById(userId, user)){
			Msg msg=new Msg(true, "停用成功", System.currentTimeMillis(), null,  "停用账户");
			return gson.toJson(msg);
		}else{
			Msg msg=new Msg(false, "停用失败", System.currentTimeMillis(), "1001",  "停用账户");
			return gson.toJson(msg);
		}
	}

	@Override
	public String getUserById(Integer userId) {
		UserView u=prisonService.getUserViewById(userId);
		if(u!=null){
			Obj obj=new Obj(true, "获取用户信息成功", u, System.currentTimeMillis(), null, "查看用户详情");
			return gson.toJson(obj);
		}else{
			
			Obj obj=new Obj(false, "获取用户信息失败", u, System.currentTimeMillis(), "10001", "查看用户详情");
			return gson.toJson(obj);
		}
	
	}

	@Override
	public String userModify(UserInfo userInfo, Integer roleId,UserPosition userPosition, HttpSession session, HttpServletRequest request) {
		if(userService.userModify(userInfo, roleId,userPosition)){
			Msg msg=new Msg(true, "修改用户成功", System.currentTimeMillis(), null, "修改用户");
			return gson.toJson(msg);
		}else{
			Msg msg=new Msg(false, "修改用户失败", System.currentTimeMillis(), "10001", "修改用户");
			return gson.toJson(msg);
		}		
	}
	@Override
	public String modifyUser(UserInfo userInfo, Integer roleId,UserPosition userPosition,int structureId,String  structureName , HttpSession session, HttpServletRequest request) {
		if(userService.userModify(userInfo, roleId,userPosition,structureId,structureName)){
			Msg msg=new Msg(true, "修改用户成功", System.currentTimeMillis(), null, "修改用户");
			return gson.toJson(msg);
		}else{
			Msg msg=new Msg(false, "修改用户失败", System.currentTimeMillis(), "10001", "修改用户");
			return gson.toJson(msg);
		}		
	}
	
	

}
